<!-- templates/add_article.html -->
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>添加新文章</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.7.2/css/all.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .text-balance {
                text-wrap: balance;
            }
        }
    </style>
    <style>
        :root {
            --primary: #3B82F6;
        }

        body {
            scroll-behavior: smooth;
        }

        input, textarea, select {
            @apply focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary;
        }

        button {
            @apply transition-all duration-200;
        }

        /* 自定义滚动条 */
        ::-webkit-scrollbar {
            width: 8px;
            height: 8px;
        }

        ::-webkit-scrollbar-track {
            background: #f1f1f1;
            border-radius: 4px;
        }

        ::-webkit-scrollbar-thumb {
            background: #c1c1c1;
            border-radius: 4px;
        }

        ::-webkit-scrollbar-thumb:hover {
            background: #a1a1a1;
        }

        /* 动画效果 */
        .fade-in {
            animation: fadeIn 0.3s ease-in-out;
        }

        @keyframes fadeIn {
            from { opacity: 0; }
            to { opacity: 1; }
        }

        .slide-up {
            animation: slideUp 0.3s ease-out;
        }

        @keyframes slideUp {
            from { transform: translateY(20px); opacity: 0; }
            to { transform: translateY(0); opacity: 1; }
        }

        /* 加载动画 */
        .loader {
            border: 3px solid rgba(255, 255, 255, 0.3);
            border-radius: 50%;
            border-top: 3px solid white;
            width: 18px;
            height: 18px;
            animation: spin 1s linear infinite;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
    </style>
</head>
<body class="bg-gray-50 font-sans">
    <div class="container mx-auto px-4 py-8 max-w-4xl">
        <header class="mb-8">
            <h1 class="text-[clamp(1.8rem,4vw,2.5rem)] font-bold text-gray-800 mb-2">添加新文章</h1>
            <p class="text-gray-600">请填写以下表单信息来发布新文章</p>
        </header>

        <form id="articleForm" class="bg-white rounded-xl shadow-lg p-6 md:p-8 mb-8 transition-all duration-300 hover:shadow-xl" enctype="multipart/form-data">
            <div class="mb-6">
                <label for="article_image" class="block text-sm font-medium text-gray-700 mb-2">文章图片</label>
                <div id="image-upload-container" class="mt-1 flex justify-center px-6 pt-5 pb-6 border-2 border-gray-300 border-dashed rounded-lg hover:border-primary transition-colors duration-200 relative overflow-hidden">
                    <!-- 默认状态显示 -->
                    <div id="drop-area" class="space-y-1 text-center w-full">
                        <i class="fa-regular fa-image text-3xl text-gray-400 mb-2"></i>
                        <div class="flex text-sm text-gray-600 justify-center">
                            <label for="file-upload" class="relative cursor-pointer bg-white rounded-md font-medium text-primary hover:text-primary/80 focus-within:outline-none">
                                <span>上传图片</span>
                                <input id="file-upload" name="article_image" type="file" class="sr-only" accept="image/*">
                            </label>
                            <p class="pl-1">或拖放文件</p>
                        </div>
                        <p class="text-xs text-gray-500" id="file-name">PNG, JPG (最大 10MB)</p>
                    </div>

                    <!-- 图片预览区域 (默认隐藏) -->
                    <div id="image-preview" class="hidden absolute inset-0 bg-white">
                        <img id="preview-image" src="" alt="预览图" class="w-full h-full object-cover">
                        <button type="button" id="remove-image" class="absolute top-2 right-2 bg-white/80 hover:bg-white text-gray-700 rounded-full p-1 transition-colors duration-200">
                            <i class="fa-regular fa-circle-xmark"></i>
                        </button>
                    </div>
                </div>
            </div>

            <div class="mb-6">
                <label for="title" class="block text-sm font-medium text-gray-700 mb-2">文章标题</label>
                <input type="text" id="title" name="title" class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary/50 focus:border-primary transition-all duration-200" placeholder="输入文章标题" required>
            </div>

            <div class="mb-6">
                <label for="article_content" class="block text-sm font-medium text-gray-700 mb-2">文章内容</label>
                <textarea id="article_content" name="article_content" rows="10" class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary/50 focus:border-primary transition-all duration-200" placeholder="输入文章内容" required></textarea>
            </div>

            <div class="grid grid-cols-1 md:grid-cols-2 gap-6 mb-6">
                <div>
                    <label for="article_tag" class="block text-sm font-medium text-gray-700 mb-2">文章标签</label>
                    <input type="text" id="article_tag" name="article_tag" class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary/50 focus:border-primary transition-all duration-200" placeholder="用逗号分隔多个标签" required>
                </div>
                <div>
                    <label for="article_type" class="block text-sm font-medium text-gray-700 mb-2">文章类型</label>
                    <select id="article_type" name="article_type" class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary/50 focus:border-primary transition-all duration-200 appearance-none bg-white" required>
                        <option value="" disabled selected>选择文章类型</option>
                        <option value="tech">技术</option>
                        <option value="lifestyle">生活方式</option>
                        <option value="entertainment">娱乐</option>
                        <option value="education">教育</option>
                        <option value="other">其他</option>
                    </select>
                </div>
            </div>

            <div class="flex flex-col sm:flex-row justify-between items-center gap-4 pt-4 border-t border-gray-200">
                <button type="button" id="previewBtn" class="flex items-center px-4 py-2 text-gray-700 bg-gray-100 rounded-lg hover:bg-gray-200 transition-colors duration-200">
                    <i class="fa-regular fa-eye mr-2"></i> 预览
                </button>
                <button type="submit" class="w-full sm:w-auto px-6 py-3 bg-primary text-dark rounded-lg hover:bg-primary/90 transition-all duration-200 shadow-md hover:shadow-lg transform hover:-translate-y-0.5 flex items-center justify-center">
                    <i class="fa-regular fa-paper-plane mr-2"></i> 发布文章
                </button>
            </div>
        </form>

        <div id="previewModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 hidden opacity-0 transition-opacity duration-300">
            <div class="bg-white rounded-xl max-w-3xl w-full max-h-[90vh] overflow-y-auto mx-4 transform transition-transform duration-300 scale-95">
                <div class="p-6 border-b border-gray-200 flex justify-between items-center">
                    <h2 class="text-xl font-bold text-gray-800">文章预览</h2>
                    <button id="closePreview" class="text-gray-500 hover:text-gray-700 transition-colors duration-200">
                        <i class="fa-solid fa-xmark text-xl"></i>
                    </button>
                </div>
                <div id="previewContent" class="p-6">
                    <!-- 预览内容将在这里动态生成 -->
                </div>
                <div class="p-6 border-t border-gray-200 flex justify-end">
                    <button id="closePreviewBtn" class="px-4 py-2 bg-gray-100 text-gray-700 rounded-lg hover:bg-gray-200 transition-colors duration-200 mr-3">
                        返回编辑
                    </button>
                    <button id="confirmPublishBtn" class="px-4 py-2 bg-primary text-dark rounded-lg hover:bg-primary/90 transition-colors duration-200">
                        确认发布
                    </button>
                </div>
            </div>
        </div>

        <div id="notification" class="fixed top-4 right-4 px-6 py-3 rounded-lg shadow-lg z-50 transform transition-all duration-300 translate-y-[-20px] opacity-0 hidden"></div>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // 获取DOM元素
            const fileUpload = document.getElementById('file-upload');
            const fileName = document.getElementById('file-name');
            const dropArea = document.getElementById('drop-area');
            const imagePreview = document.getElementById('image-preview');
            const previewImage = document.getElementById('preview-image');
            const removeImage = document.getElementById('remove-image');
            const imageUploadContainer = document.getElementById('image-upload-container');
            const previewBtn = document.getElementById('previewBtn');
            const previewModal = document.getElementById('previewModal');
            const closePreview = document.getElementById('closePreview');
            const closePreviewBtn = document.getElementById('closePreviewBtn');
            const confirmPublishBtn = document.getElementById('confirmPublishBtn');
            const previewContent = document.getElementById('previewContent');
            const articleForm = document.getElementById('articleForm');
            const notification = document.getElementById('notification');

            // 初始化marked解析器
            marked.setOptions({
                breaks: true,
                gfm: true
            });

            // 处理文件选择
            fileUpload.addEventListener('change', function() {
                handleFileSelect(this);
            });

            // 处理拖放功能
            ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
                imageUploadContainer.addEventListener(eventName, preventDefaults, false);
            });

            function preventDefaults(e) {
                e.preventDefault();
                e.stopPropagation();
            }

            ['dragenter', 'dragover'].forEach(eventName => {
                imageUploadContainer.addEventListener(eventName, highlight, false);
            });

            ['dragleave', 'drop'].forEach(eventName => {
                imageUploadContainer.addEventListener(eventName, unhighlight, false);
            });

            function highlight() {
                imageUploadContainer.classList.add('border-primary');
                imageUploadContainer.classList.add('bg-blue-50');
            }

            function unhighlight() {
                imageUploadContainer.classList.remove('border-primary');
                imageUploadContainer.classList.remove('bg-blue-50');
            }

            imageUploadContainer.addEventListener('drop', handleDrop, false);

            function handleDrop(e) {
                const dt = e.dataTransfer;
                const files = dt.files;

                if (files.length) {
                    handleFileSelect({ files });
                }
            }

            // 处理文件选择逻辑
            function handleFileSelect(input) {
                if (input.files && input.files[0]) {
                    const file = input.files[0];

                    // 检查文件类型
                    if (!file.type.match('image.*')) {
                        showNotification('请选择图片文件', 'error');
                        return;
                    }

                    // 检查文件大小 (10MB)
                    if (file.size > 10 * 1024 * 1024) {
                        showNotification('图片大小不能超过10MB', 'error');
                        return;
                    }

                    // 更新文件名显示
                    fileName.textContent = file.name;
                    fileName.classList.add('text-primary');

                    // 显示预览图
                    const reader = new FileReader();

                    reader.onload = function(e) {
                        previewImage.src = e.target.result;
                        dropArea.classList.add('hidden');
                        imagePreview.classList.remove('hidden');
                        imagePreview.classList.add('fade-in');
                    }

                    reader.readAsDataURL(file);
                }
            }

            // 移除图片
            removeImage.addEventListener('click', function() {
                // 重置文件输入
                fileUpload.value = '';

                // 恢复默认显示
                fileName.textContent = 'PNG, JPG (最大 10MB)';
                fileName.classList.remove('text-primary');
                imagePreview.classList.add('hidden');
                dropArea.classList.remove('hidden');
            });

            // 预览按钮点击事件
            previewBtn.addEventListener('click', function() {
                const title = document.getElementById('title').value;
                const content = document.getElementById('article_content').value;
                const tags = document.getElementById('article_tag').value.split(',').map(tag => tag.trim()).filter(tag => tag);
                const articleType = document.getElementById('article_type').value;
                const typeMapping = {
                    'tech': '技术',
                    'lifestyle': '生活方式',
                    'entertainment': '娱乐',
                    'education': '教育',
                    'other': '其他'
                };

                if (!title || !content || !articleType) {
                    showNotification('请填写所有必填字段', 'error');
                    return;
                }

                // 构建预览内容
                let previewHtml = `
                    <div class="space-y-6">
                        <div class="rounded-xl overflow-hidden bg-gray-100 h-64 relative">
                            ${previewImage.src ?
                                `<img src="${previewImage.src}" alt="${title}" class="w-full h-full object-cover">` :
                                `<div class="w-full h-full flex items-center justify-center text-gray-400">
                                    <i class="fa-regular fa-image text-5xl"></i>
                                </div>`
                            }
                        </div>
                        <h2 class="text-2xl font-bold text-gray-800">${title}</h2>
                        <div class="flex items-center text-sm text-gray-500 mb-4">
                            <span class="inline-flex items-center mr-4">
                                <i class="fa-regular fa-calendar mr-1"></i> ${new Date().toLocaleDateString()}
                            </span>
                            <span class="inline-flex items-center">
                                <i class="fa-solid fa-tag mr-1"></i> ${typeMapping[articleType]}
                            </span>
                        </div>
                        <div class="prose max-w-none">${marked.parse(content)}</div>
                        <div class="flex flex-wrap gap-2 mt-6">
                `;

                tags.forEach(tag => {
                    previewHtml += `
                        <span class="px-3 py-1 bg-gray-100 text-gray-700 rounded-full text-sm">
                            ${tag}
                        </span>
                    `;
                });

                previewHtml += `
                        </div>
                    </div>
                `;

                previewContent.innerHTML = previewHtml;
                previewModal.classList.remove('hidden');
                // 触发重排后添加动画类
                setTimeout(() => {
                    previewModal.classList.add('opacity-100');
                    previewModal.querySelector('div').classList.remove('scale-95');
                    previewModal.querySelector('div').classList.add('scale-100');
                }, 10);
            });

            // 关闭预览
            function closePreviewModal() {
                previewModal.classList.remove('opacity-100');
                previewModal.querySelector('div').classList.remove('scale-100');
                previewModal.querySelector('div').classList.add('scale-95');
                setTimeout(() => {
                    previewModal.classList.add('hidden');
                }, 300);
            }

            closePreview.addEventListener('click', closePreviewModal);
            closePreviewBtn.addEventListener('click', closePreviewModal);

            // 确认发布
            confirmPublishBtn.addEventListener('click', function() {
                // 收集表单数据
                const formData = new FormData(articleForm);

                // 禁用按钮并显示加载状态
                confirmPublishBtn.disabled = true;
                confirmPublishBtn.innerHTML = '<div class="loader mr-2"></div> 发布中...';

                // 提交表单数据到服务器
                fetch('/add_article', {
                    method: 'POST',
                    body: formData
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        confirmPublishBtn.innerHTML = '<i class="fa-regular fa-circle-check mr-2"></i> 发布成功!';
                        confirmPublishBtn.classList.remove('bg-primary');
                        confirmPublishBtn.classList.add('bg-green-500');

                        // 显示成功消息
                        setTimeout(function() {
                            closePreviewModal();
                            articleForm.reset();
                            fileName.textContent = 'PNG, JPG (最大 10MB)';
                            fileName.classList.remove('text-primary');
                            previewImage.src = '';
                            imagePreview.classList.add('hidden');
                            dropArea.classList.remove('hidden');

                            // 恢复按钮状态
                            setTimeout(function() {
                                confirmPublishBtn.disabled = false;
                                confirmPublishBtn.innerHTML = '<i class="fa-regular fa-paper-plane mr-2"></i> 确认发布';
                                confirmPublishBtn.classList.remove('bg-green-500');
                                confirmPublishBtn.classList.add('bg-primary');

                                // 显示全局成功通知
                                showNotification('文章发布成功！', 'success');
                            }, 1000);
                        }, 1500);
                    } else {
                        throw new Error(data.message || '发布失败，请重试');
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    confirmPublishBtn.innerHTML = '<i class="fa-regular fa-circle-xmark mr-2"></i> 发布失败';
                    confirmPublishBtn.classList.remove('bg-primary');
                    confirmPublishBtn.classList.add('bg-red-500');

                    setTimeout(function() {
                        confirmPublishBtn.disabled = false;
                        confirmPublishBtn.innerHTML = '<i class="fa-regular fa-paper-plane mr-2"></i> 确认发布';
                        confirmPublishBtn.classList.remove('bg-red-500');
                        confirmPublishBtn.classList.add('bg-primary');

                        showNotification(error.message, 'error');
                    }, 1500);
                });
            });

            // 表单提交处理
            articleForm.addEventListener('submit', function(e) {
                e.preventDefault();
                previewBtn.click();
            });

            // 显示通知
            function showNotification(message, type = 'info') {
                // 设置通知样式
                if (type === 'success') {
                    notification.className = 'fixed top-4 right-4 px-6 py-3 rounded-lg shadow-lg z-50 transform transition-all duration-300 translate-y-[-20px] opacity-0 bg-green-500 text-white';
                    notification.innerHTML = `<i class="fa-regular fa-circle-check mr-2"></i> ${message}`;
                } else if (type === 'error') {
                    notification.className = 'fixed top-4 right-4 px-6 py-3 rounded-lg shadow-lg z-50 transform transition-all duration-300 translate-y-[-20px] opacity-0 bg-red-500 text-white';
                    notification.innerHTML = `<i class="fa-regular fa-circle-xmark mr-2"></i> ${message}`;
                } else {
                    notification.className = 'fixed top-4 right-4 px-6 py-3 rounded-lg shadow-lg z-50 transform transition-all duration-300 translate-y-[-20px] opacity-0 bg-blue-500 text-white';
                    notification.innerHTML = `<i class="fa-regular fa-circle-info mr-2"></i> ${message}`;
                }

                // 显示通知
                notification.classList.remove('hidden');
                setTimeout(() => {
                    notification.classList.remove('translate-y-[-20px]', 'opacity-0');
                }, 10);

                // 自动关闭
                setTimeout(() => {
                    notification.classList.add('translate-y-[-20px]', 'opacity-0');
                    setTimeout(() => {
                        notification.classList.add('hidden');
                    }, 300);
                }, 3000);
            }
        });
    </script>
</body>
</html>
